package com.xdl.modules.wechat.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beluga.core.annotation.BelugaController;
import com.beluga.core.oss.AliOssBootService;
import com.beluga.core.oss.model.BelugaFile;
import com.beluga.core.util.Func;
import com.xdl.common.response.ResponseResult;
import com.xdl.modules.wechat.entity.SysOssFile;
import com.xdl.modules.wechat.model.OssModel;
import com.xdl.modules.wechat.service.SysOssFileService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * Oss File 前端控制器
 * </p>
 *
 * @author iron guo
 * @since 2022-05-19
 */
@AllArgsConstructor
@BelugaController("/sys/oss/file")
public class SysOssFileController {

    private SysOssFileService ossFileService;

    private AliOssBootService bootService;
    /**
     * 获取oss文件列表
     * @param model
     * @return
     */
    @PostMapping("list")
    public ResponseResult<IPage<SysOssFile>> list(@RequestBody OssModel model){
        QueryWrapper<SysOssFile> wrapper=new QueryWrapper<>();
        wrapper.lambda().like(Func.isNotEmpty(model.getFileName()),SysOssFile::getFileName,model.getFileName())
                        .like(Func.isNotEmpty(model.getUrl()),SysOssFile::getUrl,model.getUrl());
        IPage<SysOssFile> page = ossFileService.page(new Page<>(model.getPageNo(), model.getPageSize()), wrapper);
        return ResponseResult.Success(page);
    }

    @PostMapping("upload")
    public ResponseResult<Boolean> upload(@RequestParam("file") MultipartFile multipartFile) {
        BelugaFile belugaFile = bootService.putFile(multipartFile);
        SysOssFile oss=new SysOssFile();
        oss.setFileName(belugaFile.getOriginalName());
        oss.setUrl(belugaFile.getLink());
        boolean save = ossFileService.save(oss);
        return ResponseResult.Success(save);
    }

    @DeleteMapping("/delete")
    public ResponseResult<Boolean> delete(@RequestParam(name = "id") String id) {
        SysOssFile ossFile = ossFileService.getById(id);
        if(ossFile==null){
            return ResponseResult.Error("未找到该条记录");
        }else {
            ossFileService.removeById(id);
            return ResponseResult.Success("删除成功！");
        }


    }

}
